<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->

<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form v-loading="options.loading" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item prop="name" :label="t('dept.name')">
        <el-input v-model="formData.name" :placeholder="t('dept.name')"></el-input>
      </el-form-item>
      <el-form-item prop="parentName" :label="t('dept.parentName')" class="dept-list">
        <el-popover v-model="options.deptListVisible" ref="popoverRef" placement="bottom-start" trigger="click">
          <el-tree
            :data="deptList"
            :props="defaultProps"
            node-key="id"
            ref="deptListTreeRef"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion
            @current-change="deptListTreeCurrentChangeHandle"
          >
          </el-tree>
          <template #reference>
            <el-input v-model="formData.parentName" v-popover="popoverRef" :readonly="true" :placeholder="t('dept.parentName')">
              <template #suffix v-if="userStore.$state.superAdmin === 1 && formData.pid !== '0'">
                <el-icon @click.stop="deptListTreeSetDefaultHandle()"><CircleClose /></el-icon>
              </template>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item prop="order" :label="t('dept.order')">
        <el-input-number v-model="formData.order" controls-position="right" :min="0" :label="t('dept.order')"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { systemApi } from '@/api/system';
import type { ResType } from '@/utils/request';
import { ref, reactive, nextTick, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import debounce from 'lodash/debounce';
import type { ElForm, ElTree } from 'element-plus';
import { ElMessage, FormRules } from 'element-plus';
import useUseStore from '@/stores/modules/user';
import type { TreeValue } from '@/components/tcc-dept-tree/src/tcc-dept-tree.vue';

// #region 类型
interface FormData {
  id: string;
  name: string;
  pid: string;
  parentName: string;
  order: number;
}
// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();

const userStore = useUseStore();

const popoverRef = ref();
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const deptListTreeRef = ref<InstanceType<typeof ElTree> | null>(null);

const { t } = useI18n();

const dialogId = ref('0');

// 表单数据
const formData = reactive<FormData>({
  id: '',
  name: '',
  pid: '',
  parentName: '',
  order: 0,
});
// 页面配置
const options = reactive({
  visible: false,
  loading: false,
  deptListVisible: false,
});
// 部门列表
const deptList = ref<TreeValue[]>([]);
const defaultProps = ref({ label: 'name', children: 'children' });
// 验证规则
const formRules = reactive<FormRules<FormData>>({
  name: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  parentName: [{ required: true, message: t('validate.required'), trigger: 'change' }],
});
// #endregion

// #region 方法
watch([() => dialogId.value], (val1) => {
  formData.id = val1[0];
});

// 上级部门树, 设置默认值
const deptListTreeSetDefaultHandle = () => {
  formData.pid = '0';
  formData.parentName = t('dept.parentNameDefault');
};
// 上级部门树, 选中
const deptListTreeCurrentChangeHandle = (data: TreeValue) => {
  formData.pid = data.id;
  formData.parentName = data.name;
  options.deptListVisible = false;
};
// 获取部门列表
const getDeptList = async () => {
  systemApi.getDeptList().then((res) => {
    if (res?.code !== 0) {
      ElMessage.error(res.msg);
    } else {
      Object.assign(deptList.value, res.data);
    }
  });
};

// 获取部门信息
const handleGetDeptInfo = async () => {
  systemApi.getDeptInfo(formData.id).then((res) => {
    if (res?.code !== 0) {
      ElMessage.error(res.msg);
    } else {
      Object.assign(formData, formData, res.data);
      if (formData.pid === '0') {
        return deptListTreeSetDefaultHandle();
      }
      deptListTreeRef.value?.setCurrentKey(formData.pid);
    }
  });
};

const init = async () => {
  options.visible = true;
  options.loading = true;
  await nextTick();
  formRef.value?.resetFields();
  await Promise.all([getDeptList()]).then(() => {
    if (formData.id) {
      handleGetDeptInfo();
    } else if (userStore.$state.superAdmin === 1 || userStore.$state.superSubSystem === 1) {
      deptListTreeSetDefaultHandle();
    }
  });
  setTimeout(() => {
    options.loading = false;
  }, 500);
};

// 新增部门
function insertDept() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .insertDept(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新部门
function updateDept() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .updateDept(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      options.loading = true;
      let res;
      if (formData.id) {
        res = await updateDept();
      } else {
        res = await insertDept();
      }
      if (res?.code !== 0) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success(t('prompt.success'));
        options.visible = false;
        emit('refreshPageHandle');
      }
    }
  });
}
// 防抖
const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>

<style lang="scss">
.system__dept {
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
}
.el-popper {
  width: initial !important;
}
</style>
